'use client'

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { trpc } from '@/lib/trpc-provider'
import { copyToClipboard } from '@/lib/utils'
import { Copy, RotateCcw, ArrowUpDown } from 'lucide-react'

export default function Base64ConverterPage() {
  const [input, setInput] = useState('')
  const [output, setOutput] = useState('')
  const [mode, setMode] = useState<'encode' | 'decode'>('encode')
  const [error, setError] = useState('')
  const [copySuccess, setCopySuccess] = useState(false)

  const encodeMutation = trpc.tools.encodeBase64.useMutation({
    onSuccess: (data) => {
      if (data.success) {
        setOutput(data.result || '')
        setError('')
      } else {
        setError(data.error || 'Unknown error')
        setOutput('')
      }
    },
    onError: (error) => {
      setError(error.message)
      setOutput('')
    }
  })

  const decodeMutation = trpc.tools.decodeBase64.useMutation({
    onSuccess: (data) => {
      if (data.success) {
        setOutput(data.result || '')
        setError('')
      } else {
        setError(data.error || 'Unknown error')
        setOutput('')
      }
    },
    onError: (error) => {
      setError(error.message)
      setOutput('')
    }
  })

  const handleConvert = () => {
    if (!input.trim()) {
      setError('请输入要转换的内容')
      return
    }

    if (mode === 'encode') {
      encodeMutation.mutate({ text: input })
    } else {
      decodeMutation.mutate({ base64: input })
    }
  }

  const handleCopy = async () => {
    if (output) {
      const success = await copyToClipboard(output)
      if (success) {
        setCopySuccess(true)
        setTimeout(() => setCopySuccess(false), 2000)
      }
    }
  }

  const handleClear = () => {
    setInput('')
    setOutput('')
    setError('')
  }

  const handleSwapMode = () => {
    setMode(mode === 'encode' ? 'decode' : 'encode')
    // Swap input and output if both have content
    if (input && output) {
      setInput(output)
      setOutput(input)
    }
    setError('')
  }

  const isLoading = encodeMutation.isLoading || decodeMutation.isLoading

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="max-w-4xl mx-auto">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">
            Base64 转换工具
          </h1>
          <p className="text-gray-600">
            在文本和Base64编码之间进行转换，支持双向转换
          </p>
        </div>

        {/* Mode Selector */}
        <div className="flex items-center justify-center mb-6">
          <div className="flex items-center bg-gray-100 rounded-lg p-1">
            <button
              onClick={() => setMode('encode')}
              className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
                mode === 'encode'
                  ? 'bg-white text-blue-600 shadow-sm'
                  : 'text-gray-600 hover:text-gray-900'
              }`}
            >
              编码 (Text → Base64)
            </button>
            <button
              onClick={() => setMode('decode')}
              className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
                mode === 'decode'
                  ? 'bg-white text-blue-600 shadow-sm'
                  : 'text-gray-600 hover:text-gray-900'
              }`}
            >
              解码 (Base64 → Text)
            </button>
          </div>
        </div>

        {/* Controls */}
        <div className="flex flex-wrap items-center justify-center gap-4 mb-6">
          <Button onClick={handleConvert} disabled={isLoading}>
            {isLoading ? '转换中...' : mode === 'encode' ? '编码' : '解码'}
          </Button>
          
          <Button variant="outline" onClick={handleSwapMode}>
            <ArrowUpDown className="w-4 h-4 mr-2" />
            切换模式
          </Button>
          
          <Button variant="outline" onClick={handleClear}>
            <RotateCcw className="w-4 h-4 mr-2" />
            清空
          </Button>
        </div>

        {/* Main Content */}
        <div className="space-y-6">
          {/* Input */}
          <div className="space-y-2">
            <label className="text-sm font-medium text-gray-700">
              {mode === 'encode' ? '输入文本' : '输入 Base64'}
            </label>
            <textarea
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder={
                mode === 'encode'
                  ? '请输入要编码的文本内容...'
                  : '请输入要解码的Base64字符串...'
              }
              className="w-full h-32 p-4 border border-gray-300 rounded-lg font-mono text-sm resize-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>

          {/* Output */}
          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <label className="text-sm font-medium text-gray-700">
                {mode === 'encode' ? 'Base64 结果' : '解码结果'}
              </label>
              <Button 
                variant="outline" 
                size="sm" 
                onClick={handleCopy}
                disabled={!output}
              >
                <Copy className="w-4 h-4 mr-2" />
                {copySuccess ? '已复制' : '复制'}
              </Button>
            </div>
            
            {error ? (
              <div className="w-full h-32 p-4 border border-red-300 rounded-lg bg-red-50">
                <div className="text-red-600 font-medium mb-2">错误:</div>
                <div className="text-red-700 text-sm">{error}</div>
              </div>
            ) : (
              <textarea
                value={output}
                readOnly
                placeholder={
                  mode === 'encode'
                    ? 'Base64编码结果将显示在这里'
                    : '解码后的文本将显示在这里'
                }
                className="w-full h-32 p-4 border border-gray-300 rounded-lg font-mono text-sm resize-none bg-gray-50"
              />
            )}
          </div>
        </div>

        {/* Info */}
        <div className="mt-8 p-4 bg-blue-50 rounded-lg">
          <h3 className="font-semibold text-blue-900 mb-2">关于 Base64</h3>
          <p className="text-blue-700 text-sm mb-2">
            Base64是一种基于64个可打印字符来表示二进制数据的编码方式。常用于：
          </p>
          <ul className="text-blue-700 text-sm space-y-1 ml-4">
            <li>• 在URL、Cookie、网页中传输少量二进制数据</li>
            <li>• 电子邮件附件编码</li>
            <li>• 在JSON或XML中嵌入图片等二进制数据</li>
            <li>• 简单的数据混淆（注意：这不是加密）</li>
          </ul>
        </div>

        {/* Features */}
        <div className="mt-8 grid grid-cols-1 md:grid-cols-3 gap-6">
          <div className="text-center p-6 bg-green-50 rounded-lg">
            <h3 className="font-semibold text-green-900 mb-2">双向转换</h3>
            <p className="text-green-700 text-sm">
              支持文本到Base64编码和Base64到文本解码
            </p>
          </div>
          <div className="text-center p-6 bg-purple-50 rounded-lg">
            <h3 className="font-semibold text-purple-900 mb-2">实时处理</h3>
            <p className="text-purple-700 text-sm">
              快速转换，支持大文本处理
            </p>
          </div>
          <div className="text-center p-6 bg-orange-50 rounded-lg">
            <h3 className="font-semibold text-orange-900 mb-2">错误检测</h3>
            <p className="text-orange-700 text-sm">
              自动检测无效的Base64格式并提供错误提示
            </p>
          </div>
        </div>
      </div>
    </div>
  )
}